#include "wordslist.h"
#include <QFile>
#include <QDebug>

using namespace qWordCards;

WordsList::WordsList(QObject *parent) :
	QObject(parent){
}

void WordsList::AddWord(QString word) {
	if (_words.contains(word)) {return;}
	_words.insert(word);
	emit sg_WordAdded(word);
}

void WordsList::RemoveWord(QString word) {
	if (!_words.contains(word)) {return;}
	_words.remove(word);
	emit sg_WordRemoved(word);
}

bool WordsList::Contains(QString word) const {
	return _words.contains(word);
}

void WordsList::Substract(const WordsList& list) {
	_words.subtract(list._words);
}

void WordsList::Save(QString fileName) {
	QFile f(fileName);
	
	if (f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
		QSet<QString>::const_iterator i = _words.constBegin();
		while (i != _words.constEnd()) {
			if (i != _words.constBegin()){
				f.write("\n");
			}
			f.write((*i).toStdString().c_str());
			++i;
		}
		f.close();
	} else {
		qDebug() << QString("Unable to write file '%1'").arg(fileName);
	}
}

void WordsList::Load(QString fileName) {
	if (!QFile::exists(fileName)) {
		qDebug() << QString("Unable to read file '%1'. File doesn't exists").arg(fileName);
		return;
	}
	qint64 result;
	char text;
	QString tempStr;
	QFile f(fileName);
	
	_words.clear();
	
	if (f.open(QIODevice::ReadOnly)) {
		while(!f.atEnd()) {
			result = f.read(&text, sizeof(text));
			if (result == -1) {
				qDebug() << QString("Error reading file '%1'").arg(fileName);
				break;
			}
			if (text == '\n') {
				tempStr = tempStr.trimmed();
				if (tempStr != "") {
					AddWord(tempStr);
				}
				tempStr.clear();
			} else {
				tempStr.append(text);
			}
		}
		f.close();
	} else {
		qDebug() << QString("Unable to read file '%1'").arg(fileName);
	}
}
